
//
//  LJHSearchViewController.m
//  HEARME
//
//  Created by liujinhui on 16/1/29.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LJHSearchViewController.h"
#import "LJHSearchModel.h"
#import "LJHSearchResultTableView.h"
#import "LJHAlbumsDetailViewController.h"
#import "LJHAlbumsDetailCell.h"
#import "LJHAlbumListTableViewCell.h"
@interface LJHSearchViewController ()<UISearchResultsUpdating,UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain)UISearchController *searchController;
@property (nonatomic,retain)NSMutableArray *arrBtns;
@property (nonatomic,retain)NSMutableArray *myArray;
@property (nonatomic,retain)LJHSearchResultTableView *searchResultTableView;
@property (nonatomic, retain)NSMutableArray *albumArray;
@property (nonatomic ,retain) NSMutableArray *trackArray;
@property (nonatomic, retain) UILabel *myLabel;


@end

@implementation LJHSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.arrBtns = [NSMutableArray array];
    [self createSearchBar];
    
    [self createButtons];
    
    LJHBaseButton * backButton = [LJHBaseButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0 , 20, 30);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[UIImage imageNamed:@"btn_back_n@2x.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_h@2x.png"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.tabBarController.tabBar.hidden = YES;
    
    // Do any additional setup after loading the view.
}

-(void)createButtons
{
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, 80, 30)];
    lable.text = @"热门搜索";
    lable.textColor = [UIColor grayColor];
    [self.view addSubview:lable];
    
    [LJHAppTools afnGetRequest:@"http://mobile.ximalaya.com/s/hot_search_key?device=android&size=9" block:^(id result) {
        NSDictionary *dic = result;
        NSMutableArray *arr = [dic objectForKey:@"list"];
        for (int i = 0; i<3; i++) {
            for (int j = 0; j<3; j++){
                
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(i%3*((WIDTH-20*4)/3+20)+20,60 + j%3*(30+10)+20, (WIDTH-20*4)/3, 30);
                btn.tag = i;
                [btn setTitle:[arr objectAtIndex:i*3+j] forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [btn.layer setMasksToBounds:YES];
                [btn.layer setCornerRadius:12.0]; //设置矩形四个圆角半径
                [btn.layer setBorderWidth:1.0]; //边框宽度
                CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
                CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 1, 0, 0, 1 });
                [btn.layer setBorderColor:colorref];//边框颜色
                [self.view addSubview:btn];
                [self.arrBtns addObject:btn];
                
            }
        }
        
        
    } error:^(NSError *error) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"您的设备无网络访问" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertC addAction:cancelButton];
        
    }];
    if (self.searchController.searchBar.text!=nil) {
        [self.view bringSubviewToFront:self.searchResultTableView];
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
        return 2;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.albumArray.count;
    }
    else{
        return self.trackArray.count;
    }
    
    
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.searchResultTableView&&section == 0) {
        return @"专辑";
    }
    else if (tableView == self.searchResultTableView&&section == 1)
    {
        return @"声音";
    }
    
    return nil;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LJHBaseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    
//    if (tableView == self.myTableView) {
//         range = NSMakeRange(0, 0);
//        
//        LJHSearchModel *model = [self.myArray objectAtIndex:indexPath.row];
//        NSArray *strArray = [model.highlightKeyword componentsSeparatedByString:@"</em>"];
//        if (strArray.count>1) {
//            NSInteger length = ((NSString *)[strArray objectAtIndex:0]).length;
//            range =  NSMakeRange(0, length-4);
//        }
//        else
//        {
//            range = NSMakeRange(0, 0);
//        }
//        
//        NSMutableAttributedString *stringM = [[NSMutableAttributedString alloc] initWithString:self.searchController.searchBar.text];
//        [stringM addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
//        cell.textLabel.attributedText = stringM;
//        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.imgPath] placeholderImage:[UIImage imageNamed:@"1024"]
//         ];
//        return cell;
//    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (tableView == self.searchResultTableView&&indexPath.section == 0)
    {
        LJHAlbumsDetailViewController *albumsDetailVC = [[LJHAlbumsDetailViewController alloc] init];
        albumsDetailVC.navigationController.navigationBar.translucent = YES;
        [(LJHTabBarViewController *)self.tabBarController isHiddenTabBar:YES withViewController:albumsDetailVC];
        LJHAlbumModel *model = [self.albumArray objectAtIndex:indexPath.row];
        albumsDetailVC.albumId = model.myId;
        self.navigationController.navigationBarHidden = NO;
        [self.navigationController pushViewController:albumsDetailVC animated:YES];
    }
    else
    {
        LJHPlayerViewController *player = [LJHPlayerViewController sharaMusicPlayer];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
        LJHTrackModel *sing = [self.trackArray objectAtIndex:indexPath.row];
        player.song_id = sing.trackId;
        player.allMusicArray = self.trackArray;
        player.indexRow = indexPath.row;
        [self presentViewController:naVC animated:YES completion:^{
            
        }];
        
    }
    
    
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    [self.view bringSubviewToFront:self.searchResultTableView];
    NSString *searchString = [self.searchController.searchBar text];
    
    
    if ([searchString isEqualToString:@""]) {
        
        
    }
    else {
        
        [self getMoreData:searchString];
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
        return WIDTH*0.3;
    
}
-(void)backButtonAction:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark - 请求数据

-(void)getMoreData:(NSString *)cellString
{
    //    [GiFHUD setGifWithImageName:@"loading.gif"];
    //    [GiFHUD show];
    NSString *str = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?device=iphone&core=all&kw=%@&page=1&rows=3&spellchecker=true",cellString];
    
    [LJHAppTools afnGetRequest:str block:^(id result) {
        self.albumArray = [NSMutableArray array];
        self.trackArray = [NSMutableArray array];
        NSMutableArray *albumArray = [[result objectForKey:@"album"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in albumArray) {
            LJHAlbumModel *model = [LJHAlbumModel modelWithDictionary:dic];
            [self.albumArray addObject:model];
        }
        
        NSMutableArray *trackArray = [[result objectForKey:@"track"] objectForKey:@"docs"];
        for (NSMutableDictionary *dic in trackArray) {
            LJHTrackModel *model = [LJHTrackModel modelWithDictionary:dic];
            [self.trackArray addObject:model];
        }
        //        self.myLabel.alpha = 0;
        //        [GiFHUD dismiss];
        [self.searchResultTableView reloadData];
        
    } error:^(NSError *error) {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"您的设备无网络访问" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertC addAction:cancelButton];
    }];
}

#pragma mark - 创建搜索controller

-(void)createSearchBar
{
    
    self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
    //设置显示搜索结果的控制器
    self.searchController.searchResultsUpdater = self;
    //设置开始搜索时背景显示与否
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
//    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = @"搜索声音，专辑，人...";
    self.searchController.searchBar.tintColor = [UIColor colorWithRed:0.243 green:0.437 blue:0.607 alpha:1.000];
    self.searchController.searchBar.delegate = self;
    self.navigationItem.titleView = self.searchController.searchBar;
    
    
}



#pragma mark - 点击取消按钮触发方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
